package com.sunshuo.springsecuritydemo.filter;

import com.sunshuo.springsecuritydemo.pojo.VerifyCodeImage;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName VerifyCodeFilter
 * @Description 验证码过滤器
 * @Author sunshuo
 * @Date 2021/11/7 15:51
 */
@Component
public class VerifyCodeFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        /* 只有登录请求，才需要验证验证码 */
        if (StringUtils.equals("/login", request.getRequestURI())
                && StringUtils.equalsIgnoreCase("post", request.getMethod())) {
            try {
                validVerifyCode(new ServletWebRequest(request));
            } catch (AuthenticationException e) {
                // 捕获认证异常
                response.setContentType("application/json;charset=UTF-8");
                JSONObject result = new JSONObject();
                result.put("code", 500);
                result.put("message", "验证码错误");
                response.getWriter().write(result.toString());
                return;
            }
        }
        // 放过其他请求
        filterChain.doFilter(request, response);
    }

    private void validVerifyCode(ServletWebRequest request) throws ServletRequestBindingException {
        // 获取验证码
        String verifyCode = ServletRequestUtils.getStringParameter(request.getRequest(), "verifyCode");
        // 空判断
        if (StringUtils.isEmpty(verifyCode)) {
            throw new SessionAuthenticationException("验证码不能为空");
        }
        // 从session中获取验证码对象
        HttpSession session = request.getRequest().getSession();
        VerifyCodeImage verifyCodeImage = (VerifyCodeImage) session.getAttribute("SESSION_VERIFY_CODE_IMAGE_KEY");
        // session如果没有没有改对象，则抛出异常
        if (Objects.isNull(verifyCodeImage)) {
            throw new SessionAuthenticationException("验证码不存在");
        }
        // 判断验证码是否过期
        if (verifyCodeImage.isExpired()) {
            throw new SessionAuthenticationException("验证码已过期");
        }
        // 验证码是否正确
        if (!StringUtils.equals(verifyCodeImage.getCode(), verifyCode)) {
            throw new SessionAuthenticationException("验证不正确");
        }
    }
}
